import { useEffect } from "react";
import { message, Space, Select, Form } from "antd";
import { Button } from "@douyinfe/semi-ui";
import { useModel } from "umi";
import { useReactive } from "ahooks";

const SelectDatabaseVersion = ({ record }) => {
    const { selectedGateway, selectedOrganization, updateSelectedOrganization } = useModel("gateway.info");
    const { remoteData } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");

    let databaseName = record.databaseName;

    const state = useReactive({
        bntLoading: false,
        dataBaseList: [],
        selectVersionNo: {},
    });

    const getDatabaseVersions = async () => {
        let versionNo = record.dbVers || "";
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/resource/referenceDatabase/organization/getVersionByDatabaseName",
            params: { databaseName, versionNo },
        });
        state.dataBaseList = res || [];
    };

    useEffect(() => {
        if (databaseName) {
            getDatabaseVersions();
        }
    }, [databaseName]);

    const onSubmit = async () => {
        state.bntLoading = true;
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceUrl: selectedGateway.url,
            serviceName: "/organization/singleDatabaseMode/updateDatabaseStructure",
            params: { uuid: selectedOrganization.uuid, databaseName, versionNo: state.selectVersionNo },
        });
        if (res) {
            if (res?.error) {
                message.warning("升级组织数据库发生错误：" + res.error);
                state.scripts = res.scripts || [];
            } else {
                message.success("成功升级组织数据库");
                updateSelectedOrganization(res);
                onCloseGlobalModal();
            }
        }
        state.bntLoading = false;
    };

    return (
        <Space direction="vertical" size={0} style={{ width: "100%", padding: 20 }}>
            <Form.Item>
                <div>参考数据库说明: {record.title}</div>
                <div>参考数据库名称: {record.databaseName}</div>
            </Form.Item>

            <Form.Item label="数据库版本">
                <Select allowClear onChange={(value) => (state.selectVersionNo = value)}>
                    {state.dataBaseList.map((item, index) => (
                        <Select.Option key={index} value={item.versionNo}>
                            {item.versionNo}
                        </Select.Option>
                    ))}
                </Select>
            </Form.Item>
            <div style={{ textAlign: "center" }}>
                <Button loading={state.bntLoading} type="primary" onClick={onSubmit}>
                    升级数据库
                </Button>
            </div>
        </Space>
    );
};

export default SelectDatabaseVersion;
